<template>
  <div class="all-box">

    <div class="all-box-left">

      <el-card :class="{'left-box':true, 'left-box-normal': !scrolled, 'left-box-scrolled': scrolled}" style="width: 250px">
        <div class="group-card">
          <div style="font-size: 16px; font-weight: 700">
            <div>
              组卷方式：<span v-if="joinType === 1">抽题组卷</span><span v-if="joinType === 2">选题组卷</span><span v-if="joinType === 3">随机组卷</span>
            </div>
            <div>
              试题总数： <i class="num">{{ postForm.quCount }}</i>
            </div>
            <div>
              试卷总分：<i class="num">{{ postForm.totalScore }}</i>
            </div>
          </div>

          <el-button type="primary" style="width: 100%; margin-top: 20px" size="mini" @click="handleSave">保存试卷</el-button>
        </div>

        <div v-for="(item,index) in postForm.groupList" :key="item.id">
          <div class="group-card">
            <div style="line-height: 40px; vertical-align: middle;">
              <el-button style="font-size: 14px; font-weight: 700" type="text" @click="goAnchor(item.id || index)">{{ item.title }}</el-button>
              <el-divider />
              <el-popconfirm
                style="float: right"
                title="确定要删除本大题吗？"
                @confirm="removeItem(postForm.groupList, index)"
              >
                <el-button slot="reference" icon="el-icon-delete" type="text">删除</el-button>
              </el-popconfirm>
            </div>
            <div class="group-card-body">
              <div>
                共 <i class="num">{{ item.quCount }}</i> 题，共 <i class="num">{{ item.totalScore }}</i> 分
              </div>
              <div>
                每题 <el-input-number
                  v-model="item.perScore"
                  :min="0"
                  :controls="false"
                  :precision="1"
                  size="mini"
                  style="width: 60px"
                  @keyup.native="fillScore($event, item, index)"
                /> 分
              </div>
            </div>
          </div>
        </div>

      </el-card>

    </div>

    <div class="all-box-center">

      <join-top-nav :data="postForm" @create="createGroup" />

      <!-- 题目列表 -->
      <join-qu-list
        v-if="joinType===1 || joinType===2"
        ref="joinQuList"
        :group-list="postForm.groupList"
        :join-type="postForm.joinType"
        @change="calcScore"
      />

      <join-rule-list
        v-if="joinType===3"
        ref="joinQuList"
        :group-list="postForm.groupList"
        :join-type="postForm.joinType"
        @score="postForm.totalScore = $event"
        @count="postForm.quCount = $event"
      />

    </div>

  </div>
</template>

<script>
import JoinQuList from '@/views/admin/tmpl/components/components/JoinQuList'
import { apiSaveTmpl } from '@/api/tmpl/tmpl'
import JoinTopNav from '@/views/admin/tmpl/components/components/JoinTopNav'
import JoinRuleList from '@/views/admin/tmpl/components/components/JoinRuleList'
import { scrollTo } from '@/utils/scroll-to'

export default {
  name: 'Join1Form',
  components: {
    JoinRuleList,
    JoinTopNav,
    JoinQuList
  },
  props: {
    title: String,
    joinType: Number,
    catId: String,
    timeType: Number,
    data: Object
  },

  data() {
    return {
      scrolled: false,
      loading: false,
      postForm: {
        quCount: 0,
        totalScore: 0,
        title: '',
        joinType: '',
        catId: '',
        timeType: '',
        groupList: []
      }
    }
  },
  watch: {
    data: {
      handler(val) {
        if (val && val.id) {
          this.postForm = this.data
        }
      }
    },
    'postForm.groupList': {
      handler(val) {
        // 随机组卷不需要计算题目分数
        console.info(val)
        if (val && val.length > 0 && this.joinType != 3) {
          this.calcScore(val)
        }
      },
      deep: true
    }
  },

  mounted() {
    // 监听滚动条
    window.addEventListener('scroll', () => {
      let scrollTop = 0
      if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop
      } else if (document.body) {
        scrollTop = document.body.scrollTop
      }

      if (scrollTop > 85) {
        this.scrolled = true
      } else {
        this.scrolled = false
      }
    })
  },

  created() {
    // 修改
    if (this.data != null && this.data.id != null) {
      this.postForm = this.data
    } else {
      this.postForm.title = this.title
      this.postForm.joinType = this.joinType
      this.postForm.catId = this.catId
      this.postForm.timeType = this.timeType
    }
  },
  methods: {

    // 列表变化时重算分数
    calcScore(groupList) {
      // 试卷总分
      let totalScore = 0
      let quCount = 0
      for (let i = 0; i < groupList.length; i++) {
        const item = groupList[i]
        let groupScore = 0
        const quList = item.quList
        for (let j = 0; j < quList.length; j++) {
          const qu = quList[j]
          groupScore = this.$calc.add(groupScore, qu.score)
        }

        if (this.postForm.joinType !== 3) {
          item.totalScore = groupScore
          item.quCount = quList.length
        }

        quCount += item.quCount
        totalScore = this.$calc.add(totalScore, groupScore)
      }
      this.postForm.quCount = quCount
      this.postForm.totalScore = totalScore
    },

    // 左侧更改分数同步
    fillScore(event, item, index) {
      let groupScore = 0
      if (event.target.value) {
        groupScore = event.target.value * 1
      } else {
        groupScore = 0
        item.perScore = 0
      }

      const quGroup = this.postForm.groupList[index]
      const quList = quGroup.quList
      for (let i = 0; i < quList.length; i++) {
        const qu = quList[i]
        qu.score = groupScore

        // 继续赋值子题目
        if (qu.quType === '99') {
          const subList = qu.subList
          // 平均赋值到每题
          const avg = groupScore / subList.length
          // 循环中扣除，剩下的为最后一个赋值
          let left = groupScore.toFixed(1)
          // 子题目分数为大题的均值
          for (let j = 0; j < subList.length; j++) {
            // 最后一项修正分数
            if (j === subList.length - 1) {
              subList[j].score = left.toFixed(1)
            } else {
              subList[j].score = avg.toFixed(1)
              // 扣减分数
              left -= avg.toFixed(1)
            }
          }
        }
      }
      // 覆盖分数
      quGroup.quCount = quList.length
      quGroup.totalScore = groupScore * quList.length
    },

    // 移除题目
    removeItem(list, index) {
      list.splice(index, 1)
    },

    // 到指定位置
    goAnchor(selector) {
      const anchor = document.getElementById(selector)
      const to = anchor.offsetTop + 80
      scrollTo(to, 600, function() {
        console.log('滑动到指定位置！')
      })
    },

    // 创建新的大题
    createGroup(command) {
      const data = {
        anchor: new Date().getTime(),
        title: command.title,
        quType: command.quType,
        quCount: 0,
        totalScore: 0,
        perScore: 0,
        quRand: false,
        itemRand: false,
        strictSort: 0,
        quList: [],
        pathScore: false
      }
      this.postForm.groupList.push(data)

      const index = this.postForm.groupList.length - 1
      console.log('index', index)
      // 默认打开选择
      this.$refs.joinQuList.openSelectQu(index)
    },

    handleSave() {
      this.loading = true

      const check = this.checkForm()
      if (!check) {
        return
      }
      apiSaveTmpl(this.postForm).then(res => {
        this.loading = false
        this.$message.success('试卷保存成功！')
        // 回调创建好的ID
        this.$emit('back', res.data.id)
      }).catch(() => {
        this.loading = false
      })
    },

    checkForm() {
      if (!this.postForm.totalScore || this.postForm.totalScore <= 0) {
        this.$message.error('试卷总分必须大于0！')
        return false
      }

      const groupList = this.postForm.groupList

      if (groupList == null || groupList.length == 0) {
        this.$message.error('试卷必须至少包含一个大题！')
        return false
      }

      for (let i = 0; i < groupList.length; i++) {
        const group = groupList[i]
        if (group.quCount == 0) {
          this.$message.error('大题：' + group.title + ' 至少要包含一小题！')
          return false
        }

        if (!group.totalScore || group.totalScore == 0) {
          this.$message.error('大题：' + group.title + ' 总分必须大于0')
          return false
        }
      }

      return true
    }

  }
}
</script>

<style scoped>

.group-card{
  margin-bottom: 15px;
  line-height: 28px;
  width: 100%;
}

.group-card-body {
  line-height: 32px;
  font-size: 14px;
}

.group-card .num{
  color: #1890FF;
}

.left-box{
  height: calc(100vh - 120px);
  position: fixed;
  overflow: auto;
  clear: both;
}

.left-box-normal{
  top: 103px;
}

.left-box-scrolled{
  top: 20px;
  height: calc(100vh - 40px);
}

/deep/
.el-divider--horizontal{
  margin: 5px 0;
}

.all-box{
  display: flex;
  flex-direction: row
}

.all-box-left{
  width: 250px;
  flex: 0 0 250px
}

.all-box-center{
  flex-grow: 1;
  padding-left: 20px;
}

</style>
